#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/select.h>
#include<mysql.h>
#include<string.h>

struct password
{
	char id[20];
	char passwd[20];
	int flag;
};

void sign_in(int connectfd,struct password pw)
{
	MYSQL mysql;
    	MYSQL_RES *res = NULL;
    	MYSQL_ROW row;
    	char mysql_insert[100];
    	int rc,rs,fields;
	int nflag=-1;
    	if(NULL == mysql_init(&mysql)) 
	{  
	        printf("mysql_init(): %s\n", mysql_error(&mysql));  
        	return ;  
    	}  
    	if (NULL == mysql_real_connect(&mysql,  
			"localhost",  
                	"root",  
                	"root",  
                	"lts",  
                	 0,  
                	NULL,  
                	0)) 
	{  
        	printf("mysql_real_connect(): %s\n", mysql_error(&mysql));  
        	return ;  
    	}
	sprintf(mysql_insert,"select * from user where username=%d&&passwd='%s'&&fd = %d",pw.id,pw.passwd,0);
	rc = mysql_query(&mysql,mysql_insert);
	if(rc!=0)
	{
		printf("mysql_query(): %s\n", mysql_error(&mysql));
		nflag=0;
	}
	else if(rc==0)
	{
		res = mysql_store_result(&mysql);
		row = mysql_fetch_row(res);
		if(row==NULL)
		{
			sprintf(mysql_insert,"update user set fd = %d where fd = %d and username = '%s'",connectfd,0,pw.id);
			if(mysql_query(&mysql,mysql_insert))
			{
				printf("mysql_query(): %s\n", mysql_error(&mysql));
				nflag=0;
			}
			else
			{
				nflag=1;
			}
		
		}
		else
		{
			nflag=2;
		}
	}

    
	send(connectfd,&nflag,sizeof(int),0);
    	mysql_close(&mysql); 
	  
}

